package com.finstate.service.impl;

import java.text.MessageFormat;
import java.util.Locale;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;

import com.finstate.service.MessagesService;

public class MessagesServiceImpl implements MessagesService {

	private final Log logger = LogFactory.getLog(getClass());
	
	private static final String UNKNOWN_KEY_PATTERN = "??? {0} ???";
	private static final Object[] EMPTY_ARGS_ARRAY = new Object[0];

	private ReloadableResourceBundleMessageSource messageSource;
	
	public String getMessage(String key, String language) {
		return findMessage(key, EMPTY_ARGS_ARRAY, language);
	}

	public String getMessage(String key, Object[] args, String language) {
		return findMessage(key, args, language);
	}
	
	private String findMessage(String key, Object[] args, String language){
		try {
			return messageSource.getMessage(key, args, new Locale(language));
		} catch (NoSuchMessageException e) {
			logger.warn("Can't find message for key: " + key + ", language: " + language);
			return MessageFormat.format(UNKNOWN_KEY_PATTERN, key);
		}
	}

	public void setMessageSource(ReloadableResourceBundleMessageSource messageSource) {
		this.messageSource = messageSource;
	}
}
